package com.shaoyu.spring.study.validate.core;

import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * @Desc :
 * @Author: shaoyu
 * @Date : 2022/8/23 17:49
 */
public class ValidateContext extends ConcurrentHashMap<String, Object> {

    private ValidateContext() {}

    protected static Class contextClass = ValidateContext.class;

    private static final String PASS_MANDATORY_KEY = "VALIDATE_PASS_MANDATORY";

    protected static final ThreadLocal<ValidateContext> THREAD_LOCAL = InheritableThreadLocal.withInitial(()-> {
        try {
            return (ValidateContext)contextClass.newInstance();
        } catch (Throwable e) {
            return null;
        }
    });
    public static ValidateContext getCurrentContext() {
        return THREAD_LOCAL.get();
    }
    public static void remove() {
        THREAD_LOCAL.remove();
    }
    public void set(String key, Object value) {
        if (value != null){
            put(key, value);
        }else{
            remove(key);
        }
    }

    public Object getOrDefault(String key, Supplier supplier){
        Object v;
        return (v = get(key)) == null ? supplier.get() : v;
    }

    @Override
    public Object put(String key, Object value) {
        if(PASS_MANDATORY_KEY.equals(key) && !value.equals(true) ){
            throw new UnsupportedOperationException("Key["+PASS_MANDATORY_KEY+"]已占用,请使用其他字符串作为Key");
        }
        return super.put(key, value);
    }

    public static void passMandatory(){
        getCurrentContext().put(PASS_MANDATORY_KEY,true);
    }

    public static boolean skip(){
        return (boolean)getCurrentContext().getOrDefault(PASS_MANDATORY_KEY,false);
    }
}
